#!/bin/bash
PATH="$PATH:/home/tom/siweather/scripts:/usr/sbin:/bin:/usr/bin"

state=`sunsaver_state`
if [ ! "$?" -eq "0" ]; then exit 1; fi

volt=`echo $state | grep vb_f | awk '{print $3}'`
cutoff=26.0

low=`echo "$volt < $cutoff" | bc`

echo ""
echo "Battery voltage: "$volt"v (cutoff: $cutoff)"

#low=1

if [ "$low" -eq "1" ]; then
	sudo sh -c "echo 0 > /sys/class/rtc/rtc0/wakealarm"
	sudo sh -c "echo `date '+%s' -d '2300'` > /sys/class/rtc/rtc0/wakealarm"

	rtc_time=`cat /proc/driver/rtc | grep rtc_time | awk '{print $NF}'`
	rtc_date=`cat /proc/driver/rtc | grep rtc_date | awk '{print $NF}'`
	alrm_time=`cat /proc/driver/rtc | grep alrm_time | awk '{print $NF}'`
	alrm_date=`cat /proc/driver/rtc | grep alrm_date | awk '{print $NF}'`

	clock=`date +%s -d "$rtc_time $rtc_date"`
	alarm=`date +%s -d "$alrm_time $alrm_date"`
	seconds=`echo "$alarm - $clock" | bc`
	hours=`octave -q --eval "printf('%.2f',$seconds/3600)"`
	wake_datetime=`date -d "$alrm_time $alrm_date UTC"`
	
	echo ""
	echo "The current state of /proc/driver/rtc is:"
	echo ""
	cat /proc/driver/rtc
	echo ""
	echo "Clock: "$clock", Alarm: "$alarm", Difference: "$seconds" seconds ("$hours" hours)"
	echo ""
	echo "Going to halt system in 20 seconds, will sleep for "$hours" hours, waking up on "$wake_datetime". If this is wrong, hit <ctrl+c> to cancel"
	echo ""

	sleep 20
	sudo shutdown -h now
	exit 0
fi

exit 0

